package priv.stones.common.exception;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import priv.stones.common.utils.Result;
import priv.stones.common.utils.ServletHelper;
import priv.stones.controller.administrate.shiro.ShiroUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Stones
 * @Description:统一异常处理
 * @Date: 2017/10/11 11:45
 */
@RestControllerAdvice
public class StonesExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(StonesException.class)
    public ModelAndView handleStonesException(HttpServletRequest request, StonesException e) {
        return getErrorModelAndView(request, e.getMsg());
    }

    /**
     * 无权限异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(AuthorizationException.class)
    public ModelAndView handleAuthorizationException(HttpServletRequest request, AuthorizationException e) {
        logger.error("没有使用权限", e);
        return getErrorModelAndView(request, "您没有使用权限");
    }

    /**
     * 其他异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(HttpServletRequest request, Exception e) {
        logger.error(e.getMessage(), e);
        return getErrorModelAndView(request, e.getMessage());
    }

    /**
     * 得到错误的ModelAndView
     *
     * @param request
     * @param msg
     * @return
     */
    private ModelAndView getErrorModelAndView(HttpServletRequest request, String msg) {
        ModelAndView mv;
        if (!ServletHelper.isAjax(request)) {
            mv = new ModelAndView();
            mv.addObject("currAdmin", ShiroUtils.getAdmin());
            mv.addObject("body_file_path", "../error.html");
            mv.addObject("msg", msg);
            mv.setViewName("administrate/shared/layout");
        } else {
            mv = new ModelAndView(new MappingJackson2JsonView());
            mv.addAllObjects(Result.Error(msg));
        }
        return mv;
    }

}
